import { Service } from "../service";
import { ICommonItem } from "../model";
export function commonItemReducer(commonItem: ICommonItem) {
  return commonItem;
}
export const resolvers = {
  Query: {
    commonItemById: (_: any, { id }: { id: string }) =>
      Service.getCommonItemByIds([id])[0],
    commonItems: () => Service.listCommonItems(),
  },
  Mutation: {
    addCommonItem: (
      _: any,
      params: { parent: string; index?: number; title?: string }
    ) => {
      try {
        const commonItem = Service.addCommonItem(params);
        Service.save();
        const commonItems = Service.listCommonItems();
        const projects = Service.listProjects();
        return {
          success: true,
          commonItem,
          commonItems,
          projects,
        };
      } catch (err) {
        return { success: false, message: err.message };
      }
    },
    updateCommonItem: (
      _: any,
      params: {
        item: {
          id: string;
          parent?: string;
          title?: string;
          note?: string;
          index?: number;
        };
      }
    ) => {
      const commonItem = Service.updateCommonItem(params.item);
      Service.format();
      Service.save();
      const commonItems = Service.listCommonItems();
      const projects = Service.listProjects();
      return {
        success: true,
        commonItem,
        commonItems,
        projects,
      };
    },
    updateCommonItems: (
      _: any,
      params: {
        items: [
          {
            id: string;
            parent?: string;
            title?: string;
            note?: string;
            index?: number;
          }
        ];
      }
    ) => {
      params.items.forEach((p) => Service.updateCommonItem(p));
      Service.format();
      Service.save();
      const commonItems = Service.listCommonItems();
      const projects = Service.listProjects();
      return {
        success: true,
        commonItems,
        projects,
      };
    },
    removeCommonItemById: (_: any, { id }: { id: string }) => {
      const commonItem = Service.removeCommonItem(id).commonItem;
      Service.save();
      const commonItems = Service.listCommonItems();
      const projects = Service.listProjects();
      return {
        success: true,
        commonItem,
        commonItems,
        projects,
      };
    },
    removeCommonItemByIds: (_: any, { ids }: { ids: string[] }) => {
      ids.map((id) => Service.removeCommonItem(id));
      Service.save();
      const commonItems = Service.listCommonItems();
      const projects = Service.listProjects();
      return {
        success: true,
        commonItems,
        projects,
      };
    },
  },
};
